package com.jinke.uang.ui.activity.validation;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.format.Time;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jinke.uang.R;
import com.jinke.uang.base.BaseNormalActivity;
import com.jinke.uang.base.BaseResponse;
import com.jinke.uang.common.RouterMap;
import com.jinke.uang.common.NoDoubleClickListener;
import com.jinke.uang.common.UserAuthRouter;
import com.jinke.uang.common.UserInfo;
import com.jinke.uang.constant.Constant;
import com.jinke.uang.constant.HttpConstant;
import com.jinke.uang.dao.LocationDao;
import com.jinke.uang.bean.AuthUserInfoData;
import com.jinke.uang.model.AuthModule;
import com.jinke.uang.presenter.CommonPresenter;
import com.jinke.uang.bean.DictionaryItemData;
import com.jinke.uang.utils.ToastUtils;
import com.jinke.uang.view.LocationDialog;
import com.jinke.uang.view.MenuDialog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.picker.DateTimePicker;

/**
 * 个人信息认证的
 */
@Route(path = RouterMap.PERSONAL_AUTH_PAGE)
public class PersonalAuthActivity extends BaseNormalActivity <CommonPresenter,AuthModule>{

    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText)
    TextView topText;
    @BindView(R.id.etBirthday)
    TextView etBirthday;
    @BindView(R.id.rlBirthday)
    RelativeLayout rlBirthday;
    @BindView(R.id.etEdu)
    TextView etEdu;
    @BindView(R.id.rlEdu)
    RelativeLayout rlEdu;
    @BindView(R.id.etEmail)
    EditText etEmail;
    @BindView(R.id.etMotherName)
    EditText etMotherName;
    @BindView(R.id.etFamilyNum)
    TextView etFamilyNum;
    @BindView(R.id.rlFamilyNum)
    RelativeLayout rlFamilyNum;
    @BindView(R.id.etChildNum)
    TextView etChildNum;
    @BindView(R.id.rlChildNum)
    RelativeLayout rlChildNum;
    @BindView(R.id.etProvince)
    TextView etProvince;
    @BindView(R.id.rlProvince)
    RelativeLayout rlProvince;
    @BindView(R.id.etCity)
    TextView etCity;
    @BindView(R.id.rlCity)
    RelativeLayout rlCity;
    @BindView(R.id.etTown)
    TextView etTown;
    @BindView(R.id.rlTown)
    RelativeLayout rlTown;
    @BindView(R.id.etArea)
    TextView etArea;
    @BindView(R.id.rlArea)
    RelativeLayout rlArea;
    @BindView(R.id.etAddress)
    EditText etAddress;
    @BindView(R.id.etCodebig)
    EditText etCodebig;
    @BindView(R.id.etCodeSmall)
    EditText etCodeSmall;
    @BindView(R.id.etPost)
    EditText etPost;
    @BindView(R.id.etHourseType)
    TextView etHourseType;
    @BindView(R.id.rlHourseType)
    RelativeLayout rlHourseType;
    @BindView(R.id.etLiveTime)
    TextView etLiveTime;
    @BindView(R.id.rlLiveTime)
    RelativeLayout rlLiveTime;
    @BindView(R.id.etRental)
    TextView etRental;
    @BindView(R.id.rlRental)
    RelativeLayout rlRental;
    @BindView(R.id.tvNext)
    TextView tvNext;

    @Autowired(name = Constant.IS_BACK)
    boolean is_back;
    private LocationDao dao;
    private String  PERSONAGE_INFO_CODE= "personage_info_code";
    //教育
    private final String DICTIONARY_TYPE_XUELI = "common_education";
    private final String XUELI = "6";
    // 家庭成员数量
    private final String DICTIONARY_TYPE_NUMBER_OF_FAMILY_MEMBERS = "number_of_family_members";
    private final String NUMBER_OF_FAMILY_MEMBERS = "7";
    // 子女数量
    private final String DICTIONARY_TYPE_NUMBER_OF_CHILDREN = "number_of_children";
    private final String NUMBER_OF_CHILDREN = "8";

    private final String DICTIONARY_TYPE_HOURCEOWER = "common_homeowner";
    private final String HOURCEOWER = "9";

    private final String DICTIONARY_TYPE_RENTALSCOPECODE = "rental_scope";
    private final String RENTALSCOPECODE = "10";

    private DatePicker birthdayPicker;
    private DatePicker liveTimePicker;

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        topBack.setOnClickListener(viewclick);
        //获取头部信息
        topText.setText(getStringResource(R.string.work_auth_personal_information));
        rlBirthday.setOnClickListener(viewclick);
        etBirthday.setOnClickListener(viewclick);
        rlEdu.setOnClickListener(viewclick);
        etEdu.setOnClickListener(viewclick);
        rlFamilyNum.setOnClickListener(viewclick);
        etFamilyNum.setOnClickListener(viewclick);
        rlChildNum.setOnClickListener(viewclick);
        etChildNum.setOnClickListener(viewclick);
        //地址信息
        rlProvince.setOnClickListener(viewclick);
        etProvince.setOnClickListener(viewclick);
        rlCity.setOnClickListener(viewclick);
        etCity.setOnClickListener(viewclick);
        rlTown.setOnClickListener(viewclick);
        etTown.setOnClickListener(viewclick);
        rlArea.setOnClickListener(viewclick);
        etArea.setOnClickListener(viewclick);
        rlHourseType.setOnClickListener(viewclick);
        etHourseType.setOnClickListener(viewclick);
        rlLiveTime.setOnClickListener(viewclick);
        etLiveTime.setOnClickListener(viewclick);
        rlRental.setOnClickListener(viewclick);
        etRental.setOnClickListener(viewclick);
        etHourseType.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

            @Override
            public void afterTextChanged(Editable s) {
                if ("租赁".equals(etHourseType.getText().toString()) || "Lease".equals(etHourseType
                        .getText().toString()) || "KONTRAKAN/KOST".equals(etHourseType.getText()
                        .toString())) {
                    rlRental.setVisibility(View.VISIBLE);
                } else {
                    rlRental.setVisibility(View.GONE);
                }
            }
        });
        tvNext.setOnClickListener(viewclick);
    }

    /**
     * 点击信息
     */
    private NoDoubleClickListener viewclick = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            super.onNoDoubleClick(v);
            switch (v.getId()) {
                case R.id.topBack:
                    finish();
                    break;
                case R.id.rlBirthday:
                case R.id.etBirthday:
                    //生日
                    pickerBirthDay();
                    break;
                case R.id.rlEdu:
                case R.id.etEdu:
                    //学历
                    picker_edu();
                    break;
                case R.id.rlFamilyNum:
                case R.id.etFamilyNum:
                    //家庭数量
                    pickerFamily();
                    break;
                case R.id.rlChildNum:
                case R.id.etChildNum:
                    //子女数量
                    pickerChild();
                    break;
                case R.id.rlProvince:
                case R.id.etProvince:
                    pickerProvince();
                    break;
                case R.id.rlCity:
                case R.id.etCity:
                    pickerCity();
                    break;
                case R.id.rlTown:
                case R.id.etTown:
                    pickerTown();
                    break;
                case R.id.rlArea:
                case R.id.etArea:
                    pickerArea();
                    break;
                case R.id.rlHourseType:
                case R.id.etHourseType:
                    //房屋类型
                    pickerHourseType();
                    break;
                case R.id.rlRental:
                case R.id.etRental:
                    //租金级别
                    pickerRental_scope();
                    break;
                case R.id.rlLiveTime:
                case R.id.etLiveTime:
                    //入住时间
                    pickerLiveTime();
                    break;
                case R.id.tvNext:
                    commit();
                    break;
                default:
                    break;
            }
        }
    };

    private void pickerRental_scope() {
        getMenuDialog().showDialog(etRental, mRentalScope);
    }

    /**
     * 生日弹框
     */
    private void pickerBirthDay() {
        if (birthdayPicker == null) {
            //24小时值
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            String year = sdf.format(new Date());
            birthdayPicker = new DatePicker(this, DateTimePicker.YEAR_MONTH_DAY);
            //日期起点
            birthdayPicker.setRangeStart(Integer.parseInt(year) - 50, 1, 1);
            //日期终点
            birthdayPicker.setRangeEnd(Integer.parseInt(year) - 15, 1, 1);
            // 设置默认选中值
            birthdayPicker.setSelectedItem(Integer.parseInt(year) - 25, 1, 1);

            birthdayPicker.setLabel(getStringResource(R.string.year_unit), getStringResource(R
                    .string.month_unit), getStringResource(R.string.day_unit));
            birthdayPicker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                @Override
                public void onDatePicked(String year, String month, String day) {
                    etBirthday.setText(year + "-" + month + "-" + day);
                }
            });
        }
        birthdayPicker.show();
    }

    /**
     * 居住时间
     */
    private void pickerLiveTime() {
        Time time = new Time();
        time.setToNow();
        int year = time.year;
        int month = time.month + 1;
        if (liveTimePicker == null) {

            liveTimePicker = new DatePicker(this, DateTimePicker.YEAR_MONTH);
            liveTimePicker.setLabel(getStringResource(R.string.year_unit), getStringResource(R
                    .string.month_unit), getStringResource(R.string.day_unit));
            //日期起点
            liveTimePicker.setRangeStart(year - 30, 1);
            //日期终点
            liveTimePicker.setRangeEnd(year, month);
            // 设置默认选中值
            liveTimePicker.setSelectedItem(year, 1);

            liveTimePicker.setOnDatePickListener(new DatePicker.OnYearMonthPickListener() {
                @Override
                public void onDatePicked(String year, String month) {
                    etLiveTime.setText(year + "-" + month);
                }
            });
        }
        liveTimePicker.show();
    }

    private void pickerHourseType() {
        getMenuDialog().showDialog(etHourseType, mHourceowerList);
    }

    @Override
    protected void onUIReady() {
        ARouter.getInstance().inject(this);
        dao = new LocationDao();
        if (UserInfo.isShowUserInformation()) {
            mPresenter.getData(HttpConstant.MONEY_AUTH_INFO_DATA,null,PERSONAGE_INFO_CODE);
        }
        if (is_back) {
            tvNext.setText(R.string.save_change);
        }

        mPresenter.getData(HttpConstant.DICTIONARY_DATA,XUELI,DICTIONARY_TYPE_XUELI);
        mPresenter.getData(HttpConstant.DICTIONARY_DATA,NUMBER_OF_FAMILY_MEMBERS,DICTIONARY_TYPE_NUMBER_OF_FAMILY_MEMBERS);
        mPresenter.getData(HttpConstant.DICTIONARY_DATA,NUMBER_OF_CHILDREN,DICTIONARY_TYPE_NUMBER_OF_CHILDREN);
        mPresenter.getData(HttpConstant.DICTIONARY_DATA,HOURCEOWER,DICTIONARY_TYPE_HOURCEOWER);
        mPresenter.getData(HttpConstant.DICTIONARY_DATA,RENTALSCOPECODE,DICTIONARY_TYPE_RENTALSCOPECODE);
        showLoadingView();
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_auth_personinfo;
    }

    @Override
    protected int getResId() {
        return 0;
    }

    @Override
    public String getPageTitle() {
        return null;
    }

    @Override
    protected CommonPresenter getPresenter() {
        return new CommonPresenter();
    }

    @Override
    protected AuthModule getModule() {
        return new AuthModule();
    }

    private void pickerFamily() {
        getMenuDialog().showDialog(etFamilyNum, mFamilyList);
    }

    private void pickerProvince() {
        getLocationDialog().showDialog(etProvince, mProvinces);
    }

    private void pickerCity() {
        String province = etProvince.getText().toString();
        mCitys = dao.getCity(province);
        getLocationDialog().showDialog(etCity, mCitys);

    }

    private void pickerTown() {
        String province = etProvince.getText().toString();
        String city = etCity.getText().toString();
        mTowns = dao.getTown(province, city);
        getLocationDialog().showDialog(etTown, mTowns);
    }

    private void pickerArea() {
        String province = etProvince.getText().toString();
        String city = etCity.getText().toString();
        String town = etTown.getText().toString();
        mAreas = dao.getArea(province, city, town);
        getLocationDialog().showDialog(etArea, mAreas);
    }

    private void pickerChild() {
        getMenuDialog().showDialog(etChildNum, mChildList);
    }

    private void picker_edu() {
        getMenuDialog().showDialog(etEdu, mXueliList);
    }

    private MenuDialog mMenuDialog;
    public MenuDialog getMenuDialog() {
        if (mMenuDialog == null) {
            mMenuDialog = new MenuDialog(this, R.style.dialog_bottom_full);
        }
        return mMenuDialog;
    }
    private LocationDialog mLocationDialog;

    public LocationDialog getLocationDialog() {
        if (mLocationDialog == null) {
            mLocationDialog = new LocationDialog(this, R.style.dialog_bottom_full);
        }
        return mLocationDialog;
    }

    /**
     * 设置回显信息
     *
     * @param personageInfo
     */
    private void fillTextView(AuthUserInfoData.PersonageInfoBean personageInfo) {
        etBirthday.setText(personageInfo.getBirthday());
        etEdu.setText(personageInfo.getEducationValue());
        etEdu.setTag(personageInfo.getEducation());
        etEmail.setText(personageInfo.getEmail());
        etMotherName.setText(personageInfo.getMotherName());
        etFamilyNum.setText(personageInfo.getFamilyNumValue());
        etFamilyNum.setTag(personageInfo.getFamilyNum());
        etChildNum.setText(personageInfo.getSonsNumValue());
        etChildNum.setTag(personageInfo.getSonsNum());
        etProvince.setText(personageInfo.getProvince());
        etCity.setText(personageInfo.getCity());
        etTown.setText(personageInfo.getTown());
        etArea.setText(personageInfo.getRegion());
        etAddress.setText(personageInfo.getAddress());
        etCodebig.setText(personageInfo.getBigRegionCode());
        etCodeSmall.setText(personageInfo.getSmallRegionCode());
        etPost.setText(personageInfo.getZipCode());
        etHourseType.setText(personageInfo.getHomeownerValue());
        etHourseType.setTag(personageInfo.getHomeowner());
        etLiveTime.setText(personageInfo.getResidenceStartTime());
        etRental.setText(personageInfo.getRentalScopeValue());
        etRental.setTag(personageInfo.getRentalScopeCode());
    }

    private ArrayList<DictionaryItemData> mXueliList;
    private ArrayList<DictionaryItemData> mFamilyList;
    private ArrayList<DictionaryItemData> mChildList;
    private ArrayList<DictionaryItemData> mRentalScope;
    private ArrayList<DictionaryItemData> mHourceowerList;
    private ArrayList<String> mProvinces;
    private ArrayList<String> mCitys;
    private ArrayList<String> mTowns;
    private ArrayList<String> mAreas;

    private void commit() {
        String birthDay = etBirthday.getText().toString().trim();
        String edu = (String) etEdu.getTag();
        String e_mail = etEmail.getText().toString().trim();
        String motherName = etMotherName.getText().toString().trim();
        String familyNum = (String) etFamilyNum.getTag();
        String childNum = (String) etChildNum.getTag();
        String province = etProvince.getText().toString().trim();
        String city = etCity.getText().toString().trim();
        String town = etTown.getText().toString().trim();
        String area = etArea.getText().toString().trim();
        String address = etAddress.getText().toString().trim();
        String bigCode = etCodebig.getText().toString().trim();
        String smallCode = etCodeSmall.getText().toString().trim();
        String postNo = etPost.getText().toString().trim();
        String hourseType = (String) etHourseType.getTag();
        String liveTime = etLiveTime.getText().toString().trim();
        String rentalScopeCode = (String) etRental.getTag();
        if (TextUtils.isEmpty(birthDay)) {
            ToastUtils.showShort(this, R.string.personal_auth_birthday_hint);
            return;
        } else if (TextUtils.isEmpty(edu)) {
            ToastUtils.showShort(this, R.string.personal_auth_edu_hint);
            return;
        } else if (TextUtils.isEmpty(e_mail)) {
            ToastUtils.showShort(this, R.string.personal_auth_e_mail_hint);
            return;
        } else if (TextUtils.isEmpty(motherName)) {
            ToastUtils.showShort(this, R.string.personal_auth_mother_name_hint);
            return;
        } else if (TextUtils.isEmpty(familyNum)) {
            ToastUtils.showShort(this, R.string.personal_auth_family_num_hint);
            return;
        } else if (TextUtils.isEmpty(childNum)) {
            ToastUtils.showShort(this, R.string.personal_auth_child_num_hint);
            return;
        } else if (TextUtils.isEmpty(province)) {
            ToastUtils.showShort(this, R.string.personal_auth_province_hint);
            return;
        } else if (TextUtils.isEmpty(city)) {
            ToastUtils.showShort(this, R.string.personal_auth_city_hint);
            return;
        } else if (TextUtils.isEmpty(town)) {
            ToastUtils.showShort(this, R.string.personal_auth_town_hint);
            return;
        } else if (TextUtils.isEmpty(area)) {
            ToastUtils.showShort(this, R.string.personal_auth_area_hint);
            return;
        } else if (TextUtils.isEmpty(address)) {
            ToastUtils.showShort(this, R.string.personal_auth_address_hint);
            return;
        } else if (TextUtils.isEmpty(bigCode)) {
            ToastUtils.showShort(this, R.string.personal_auth_code_big_hint);
            return;
        } else if (TextUtils.isEmpty(smallCode)) {
            ToastUtils.showShort(this, R.string.personal_auth_code_small_hint);
            return;
        } else if (TextUtils.isEmpty(postNo)) {
            ToastUtils.showShort(this, R.string.personal_auth_post_hint);
            return;
        } else if (TextUtils.isEmpty(hourseType)) {
            ToastUtils.showShort(this, R.string.personal_auth_hourse_type_hint);
            return;
        } else if (TextUtils.isEmpty(liveTime)) {
            ToastUtils.showShort(this, R.string.personal_auth_live_time_hint);
            return;
        }
        if ("租赁".equals(etHourseType.getText().toString()) || "Lease".equals(etHourseType.getText
                ().toString()) || "KONTRAKAN/KOST".equals(etHourseType.getText().toString())) {
            if (TextUtils.isEmpty(rentalScopeCode)) {
                ToastUtils.showShort(this, R.string.personal_auth_rental_scope_hint);
                return;
            }
        }

            mPresenter.getData(HttpConstant.PERSONAL_SAVE_PERSONAL_AUTH,null,birthDay,edu,e_mail,motherName,familyNum,childNum,province,
                    city,town,area,address,postNo,bigCode,smallCode,liveTime,hourseType,rentalScopeCode,PERSONAGE_INFO_CODE);
        showLoadingView();
    }



    @Override
    public void showResponse(int apiType, String listType, Object o) { //个人信息认证
        dismissLoadingView();
        if(apiType== HttpConstant.MONEY_AUTH_INFO_DATA){
            dismissLoadingView();
            BaseResponse<AuthUserInfoData> response = (BaseResponse<AuthUserInfoData>) o;
            fillTextView(response.getData().getPersonageInfo());
        }

        else if(apiType==HttpConstant.PERSONAL_SAVE_PERSONAL_AUTH){ //个人信息提交
            dismissLoadingView();
            BaseResponse<String> response = (BaseResponse<String>) o;
            if (response.getStatus() == Constant.HTTP_OK) {
                //CONTACT_AUTH_PAGE联系人    PERSONAL_AUTH_PAGE个人信息
                if (!is_back) {
                    UserAuthRouter.getInstance().jumpNextPager(this, RouterMap.PERSONAL_AUTH_PAGE);
                } else {
                    finish();
                }
            } else {
                ToastUtils.showShort(this, response.getMessage());
            }
        }

        else if(apiType== HttpConstant.DICTIONARY_DATA){//获取字典信息
            dismissLoadingView();
            if(listType.equals(XUELI)){
                BaseResponse<ArrayList<DictionaryItemData>> response = (BaseResponse<ArrayList<DictionaryItemData>>) o;
                mXueliList=response.getData();
            }
            else if(listType.equals(NUMBER_OF_FAMILY_MEMBERS)){
                BaseResponse<ArrayList<DictionaryItemData>> response = (BaseResponse<ArrayList<DictionaryItemData>>) o;
                mFamilyList=response.getData();
            }
            else if(listType.equals(NUMBER_OF_CHILDREN)){
                BaseResponse<ArrayList<DictionaryItemData>> response = (BaseResponse<ArrayList<DictionaryItemData>>) o;
                mChildList=response.getData();
            }
            else if(listType.equals(HOURCEOWER)){
                BaseResponse<ArrayList<DictionaryItemData>> response = (BaseResponse<ArrayList<DictionaryItemData>>) o;
                mHourceowerList=response.getData();
            }
            else if(listType.equals(RENTALSCOPECODE)){
                BaseResponse<ArrayList<DictionaryItemData>> response = (BaseResponse<ArrayList<DictionaryItemData>>) o;
                mRentalScope=response.getData();
            }
            mProvinces = dao.getProvince();
        }
    }

    @Override
    public void showError(Throwable e) {
        dismissLoadingView();
    }
}
